<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Requests;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\Rule;

/**
 * 信息模型模块表单验证
 * Class InfoModelRequest
 * @package App\Http\Requests
 */
class InfoModelRequest extends BaseRequest
{

    /**
     * 注入表单请求验证时自动校验
     *
     * @var bool
     */
    public $autoValidate = false;

    /**
     * 用户是否有权操作，true是，false否
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 字段验证规则
     *
     * @return array
     */
    public function rules()
    {
        $info_model = $this->info_model;
        return [
            'id' => 'required|integer',
            'created_user_id' => 'required|integer',
            'name' => ['required', 'min:2', 'max:30', Rule::unique('info_model')->ignore($info_model)->where(function ($query) {
                return $query->where('deleted_at', null);
            })],
            'table_name' => ['required', 'min:2', 'max:50', Rule::unique('info_model')->ignore($info_model)->where(function ($query) {
                return $query->where('deleted_at', null);
            }), function ($attribute, $value, $fail) {
                if (!Schema::hasTable($value)) {
                    $fail(__('infoModel.error_table_name_not_created'));
                }
            }
            ],
//            'status' => 'required|boolean'
        ];
    }

    /**
     * 提示信息
     * @return array
     */
    public function messages()
    {
        return [
        ];
    }

    /**
     * 定义场景
     * @var \string[][]
     */
    public $scenes = [
        'store' => ['created_user_id', 'name', 'table_name'],
        'update' => ['name', 'table_name'],
        'destroy' => ['id']
    ];

    /**
     * 验证错误的自定义属性
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'id' => __('common.id'),
            'name' => __('infoModel.name'),
            'table_name' => __('infoModel.table_name'),
        ];
    }

    /**
     * 验证前
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        $this->offsetSet('created_user_id', Auth::id());
    }
}
